/**
 * ChatWindow 通话相关逻辑模块
 * 包含语音/视频通话、群聊通话等功能
 */

import { ref, type ComputedRef, toRef } from 'vue'
import { useQuasar } from 'quasar'
import { useChatStore } from '../stores/chat'

export interface CallInviteData {
  fromUserId: string
  fromUserName: string
  isVoiceOnly: boolean
  messageId: string
  timeout: number
}

export interface GroupMember {
  member_id: string
  displayName: string
  alias?: string
  avatar?: string
  role?: number
}

/**
 * 创建通话相关功能
 */
export function useChatWindowCall(
  chatStore: ReturnType<typeof useChatStore>,
  currentTargetId: ComputedRef<string | null>,
  targetType: ComputedRef<'User' | 'Group'>,
  targetName: ComputedRef<string>,
  getUserInitial: (userId: string) => string
) {
  const $q = useQuasar()
  
  // 通话状态
  const showVideoCall = ref(false)
  const isVoiceCall = ref(false)
  const isGroupCall = ref(false)
  const videoCallTargetUserId = ref<string | null>(null)
  const videoCallTargetName = ref<string | null>(null)
  const callInviteData = ref<CallInviteData | null>(null)
  const showGroupCallDialog = ref(false)
  const groupCallMembers = ref<GroupMember[]>([])

  /**
   * 处理语音通话（单聊）
   */
  const handleVoiceCall = async () => {
    // 优先使用临时通话目标（如果设置了），否则使用当前目标
    const targetId = videoCallTargetUserId.value || currentTargetId.value
    const target = videoCallTargetName.value || targetName.value
    
    if (!targetId) {
      $q.notify({
        type: 'warning',
        message: '请先选择聊天对象',
        position: 'top',
      })
      return
    }
    
    // 单聊通话：重置群聊标志
    isGroupCall.value = false
    
    if (targetType.value === 'Group' && !videoCallTargetUserId.value) {
      $q.notify({
        type: 'warning',
        message: '群组暂不支持语音通话',
        position: 'top',
      })
      return
    }
    
    try {
      // 先发送通话邀请消息
      const { sendCallInvite } = await import('../stores/chat-message-sender')
      await sendCallInvite(
        targetId,
        true, // isVoiceOnly
        30, // timeout: 30秒
        toRef(chatStore, 'currentUserId')
      )
      
      // 使用对话框模式，不创建独立窗口
      isVoiceCall.value = true
      showVideoCall.value = true
    } catch (error: any) {
      console.error('发送通话邀请失败:', error)
      $q.notify({
        type: 'negative',
        message: error.message || '发送通话邀请失败',
        position: 'top',
      })
    }
  }

  /**
   * 处理视频通话（单聊）
   */
  const handleVideoCall = async () => {
    // 优先使用临时通话目标（如果设置了），否则使用当前目标
    const targetId = videoCallTargetUserId.value || currentTargetId.value
    const target = videoCallTargetName.value || targetName.value
    
    if (!targetId) {
      $q.notify({
        type: 'warning',
        message: '请先选择聊天对象',
        position: 'top',
      })
      return
    }
    
    // 单聊通话：重置群聊标志
    isGroupCall.value = false
    
    if (targetType.value === 'Group' && !videoCallTargetUserId.value) {
      $q.notify({
        type: 'warning',
        message: '群组暂不支持视频通话',
        position: 'top',
      })
      return
    }
    
    try {
      // 先发送通话邀请消息
      const { sendCallInvite } = await import('../stores/chat-message-sender')
      await sendCallInvite(
        targetId,
        false, // isVoiceOnly
        30, // timeout: 30秒
        toRef(chatStore, 'currentUserId')
      )
      
      // 使用对话框模式，不创建独立窗口
      isVoiceCall.value = false
      showVideoCall.value = true
    } catch (error: any) {
      console.error('发送通话邀请失败:', error)
      $q.notify({
        type: 'negative',
        message: error.message || '发送通话邀请失败',
        position: 'top',
      })
      // 如果创建窗口失败，回退到对话框模式
      isVoiceCall.value = false
      showVideoCall.value = true
    }
  }

  /**
   * 处理群组语音通话
   */
  const handleGroupVoiceCall = async (memberIds: string[]) => {
    try {
      if (memberIds.length === 0) {
        $q.notify({
          type: 'warning',
          message: '请至少选择一个成员',
          position: 'top',
        })
        return
      }
      
      // 群聊通话：使用群聊ID和选中的成员列表
      const selectedMembers = groupCallMembers.value.filter(m => memberIds.includes(m.member_id))
      
      // 设置群聊通话信息
      isGroupCall.value = true
      groupCallMembers.value = selectedMembers
      videoCallTargetUserId.value = currentTargetId.value || ''
      videoCallTargetName.value = targetName.value || ''
      
      // 打开通话窗口（使用对话框模式，因为群聊需要显示成员列表）
      isVoiceCall.value = true
      showVideoCall.value = true
    } catch (error: any) {
      console.error('发起群组语音通话失败:', error)
      $q.notify({
        type: 'negative',
        message: error.message || '发起语音通话失败',
        position: 'top',
      })
    }
  }

  /**
   * 处理群组视频通话
   */
  const handleGroupVideoCall = async (memberIds: string[]) => {
    try {
      if (memberIds.length === 0) {
        $q.notify({
          type: 'warning',
          message: '请至少选择一个成员',
          position: 'top',
        })
        return
      }
      
      // 群聊通话：使用群聊ID和选中的成员列表
      const selectedMembers = groupCallMembers.value.filter(m => memberIds.includes(m.member_id))
      
      // 设置群聊通话信息
      isGroupCall.value = true
      groupCallMembers.value = selectedMembers
      videoCallTargetUserId.value = currentTargetId.value || ''
      videoCallTargetName.value = targetName.value || ''
      
      // 打开通话窗口（使用对话框模式，因为群聊需要显示成员列表）
      isVoiceCall.value = false
      showVideoCall.value = true
    } catch (error: any) {
      console.error('发起群组视频通话失败:', error)
      $q.notify({
        type: 'negative',
        message: error.message || '发起视频通话失败',
        position: 'top',
      })
    }
  }

  /**
   * 处理通话结束
   */
  const handleCallEnded = () => {
    // 重置群聊标志
    isGroupCall.value = false
    showVideoCall.value = false
    isVoiceCall.value = false
    // 注意：videoCallTargetUserId 和 videoCallTargetName 的清除在 onClose 回调中处理
  }

  /**
   * 处理通话邀请接受
   */
  const handleCallInviteAccept = async (data: CallInviteData) => {
    try {
      callInviteData.value = null
      
      // 设置通话目标
      videoCallTargetUserId.value = data.fromUserId
      videoCallTargetName.value = data.fromUserName
      
      // 使用对话框模式，不创建独立窗口
      isVoiceCall.value = data.isVoiceOnly
      showVideoCall.value = true
    } catch (error: any) {
      console.error('接听通话失败:', error)
      $q.notify({
        type: 'negative',
        message: error.message || '接听通话失败',
        position: 'top',
      })
    }
  }

  /**
   * 处理通话邀请拒绝
   */
  const handleCallInviteReject = (data: CallInviteData) => {
    callInviteData.value = null
    console.log('拒绝通话邀请:', data)
  }

  /**
   * 处理通话邀请超时
   */
  const handleCallInviteTimeout = (data: CallInviteData) => {
    callInviteData.value = null
    $q.notify({
      type: 'warning',
      message: '通话邀请已超时',
      position: 'top',
    })
    console.log('通话邀请超时:', data)
  }

  /**
   * 处理显示群组通话成员选择对话框
   */
  const handleShowGroupCallDialog = async () => {
    try {
      // 检查是否是群组
      if (targetType.value !== 'Group') {
        $q.notify({
          type: 'warning',
          message: '当前不是群组聊天',
          position: 'top',
        })
        return
      }

      // 检查是否有群组ID
      if (!currentTargetId.value) {
        $q.notify({
          type: 'warning',
          message: '请先选择群组',
          position: 'top',
        })
        return
      }

      // 获取群组成员列表
      const { getGroupMembers } = await import('../services/im-group')
      const { getUser } = await import('../services/message')
      const { getUserAsync } = await import('../services/auth')
      
      // 标准化群组ID（确保以 group_ 开头）
      const normalizedGroupId = currentTargetId.value.startsWith('group_') 
        ? currentTargetId.value 
        : `group_${currentTargetId.value}`
      
      const members = await getGroupMembers(normalizedGroupId, false)
      
      // 获取当前用户ID，用于过滤掉自己
      const currentUser = await getUserAsync()
      const currentUserId = currentUser?.open_id || 
        (currentUser?.snowflake_id ? String(currentUser.snowflake_id) : undefined) || 
        (currentUser ? String(currentUser.id) : undefined)
      
      // 获取每个成员的用户信息，显示username而不是openid
      const membersWithUserInfo = await Promise.all(
        members
          .filter(m => m.member_id !== currentUserId) // 过滤掉自己
          .map(async (member) => {
            try {
              const userInfo = await getUser(member.member_id)
              return {
                member_id: member.member_id,
                displayName: userInfo?.name || member.alias || member.member_id,
                alias: member.alias,
                role: member.role,
              } as GroupMember
            } catch (e: any) {
              return {
                member_id: member.member_id,
                displayName: member.alias || member.member_id,
                alias: member.alias,
                role: member.role,
              } as GroupMember
            }
          })
      )
      
      // 检查是否有可用的成员
      if (membersWithUserInfo.length === 0) {
        $q.notify({
          type: 'warning',
          message: '群组中没有其他成员',
          position: 'top',
        })
        return
      }
      
      // 设置群组成员列表
      groupCallMembers.value = membersWithUserInfo
      
      // 显示对话框
      showGroupCallDialog.value = true
    } catch (error: any) {
      console.error('显示群组通话对话框失败:', error)
      $q.notify({
        type: 'negative',
        message: error.message || '显示群组通话对话框失败',
        position: 'top',
      })
    }
  }

  return {
    // 状态
    showVideoCall,
    isVoiceCall,
    isGroupCall,
    videoCallTargetUserId,
    videoCallTargetName,
    callInviteData,
    showGroupCallDialog,
    groupCallMembers,
    // 方法
    handleVoiceCall,
    handleVideoCall,
    handleGroupVoiceCall,
    handleGroupVideoCall,
    handleCallEnded,
    handleCallInviteAccept,
    handleCallInviteReject,
    handleCallInviteTimeout,
    handleShowGroupCallDialog,
  }
}

